/**
 * @title auth守卫
 * @Author webxue
 * @Date 2022/12/02
 */

import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { AuthGuard } from "@nestjs/passport";
import { AuthKeyword, StatusCode } from "src/utils/Mapping";

@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {
  constructor(private reflector: Reflector) {
    super();
  }

  // 处理接口是否需要token
  canActivate(context: ExecutionContext) {
    const isPublic = this.reflector.getAllAndOverride(AuthKeyword.NoToken, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) return true;

    return super.canActivate(context);
  }

  // 处理token校验
  handleRequest(err: Error, user: any, info: any) {
    if (err || !user) {
      throw (
        err ||
        new UnauthorizedException({
          code: StatusCode.NoAuth,
          message: "登录失效",
        })
      );
    }

    return user;
  }
}
